package com.letoken.platform.app.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.letoken.platform.app.configuration.PancakeSwapLPQuery;
import com.letoken.platform.app.service.AppBalanceService;
import com.letoken.platform.app.service.AppUserWalletService;
import com.letoken.platform.pub.annotation.auth.NotAuthorization;
import com.letoken.platform.pub.constant.ConstantsValue;
import com.letoken.platform.pub.enums.BalanceTypeEnum;
import com.letoken.platform.pub.enums.LetokenApiResponseEnum;
import com.letoken.platform.pub.enums.LetokenTokenTypeEnum;
import com.letoken.platform.pub.enums.TokenTransactionTypeEnum;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.pub.req.PageData;
import com.letoken.platform.pub.res.ApiResponse;
import com.letoken.platform.pub.util.LocalDateTool;
import com.letoken.platform.repo.app.dao.*;
import com.letoken.platform.repo.app.po.AppUserWallet;
import com.letoken.platform.repo.app.req.user.BalanceHistoryReq;
import com.letoken.platform.repo.app.req.user.BalanceTransferReq;
import com.letoken.platform.repo.app.req.user.LpLockHistoryReq;
import com.letoken.platform.repo.app.res.user.*;
import com.letoken.platform.repo.utlis.PageDataUtil;
import com.letoken.platform.repo.utlis.WebUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/lp")
public class AppLpController {



    @Autowired
    AppUserWalletMapper appUserWalletMapper;
    @Autowired
    AppLpLockHistoryMapper appLpLockHistoryMapper;

    @GetMapping("/query")
    public ApiResponse<AppLpRes> balanceQuery() {
        LambdaQueryWrapper<AppUserWallet> lqwAuw = new LambdaQueryWrapper<>();
        lqwAuw.eq(AppUserWallet::getUserId,WebUtils.getUserId()).eq(AppUserWallet::getTokenId,LetokenTokenTypeEnum.LP.getId());
        AppUserWallet w = appUserWalletMapper.selectOne(lqwAuw);
        if (ObjectUtils.isEmpty(w)){
            return ApiResponse.create();
        }
        AppLpRes res = new AppLpRes();
        res.setReleasedBalance(w.getReleasedBalance());
        res.setAvailableBalance(w.getAvailableBalance());
        return ApiResponse.create(res);
    }

    @PostMapping(value = "/lockHistory")
    public ApiResponse<PageData<AppLpLockHistoryRes>> history(@Validated @RequestBody LpLockHistoryReq req ) {
        Integer userId = WebUtils.getUserId();
        req.setUserId(userId);
        Page<AppLpLockHistoryRes> page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        Page<AppLpLockHistoryRes> detailPage = appLpLockHistoryMapper.history(page,req);
        return ApiResponse.create(PageDataUtil.getPageData(detailPage));
    }




    @PostMapping(value = "/assetHistory")
    public ApiResponse<PageData<AppLpAssetHistoryRes>> assetHistory(@Validated @RequestBody LpLockHistoryReq req ) {
        Integer userId = WebUtils.getUserId();
        req.setUserId(userId);
        Page<AppLpAssetHistoryRes> page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        Page<AppLpAssetHistoryRes> detailPage = appLpLockHistoryMapper.assetHistory(page,req);
        return ApiResponse.create(PageDataUtil.getPageData(detailPage));
    }

    @GetMapping("/test")
    @NotAuthorization
    public ApiResponse test(@RequestParam("userId") Integer userId,@RequestParam("lp") BigDecimal lp) {
        try {
            addCAP(userId,lp,"");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ApiResponse.create();
    }

    @GetMapping("/getprice")
    @NotAuthorization
    public ApiResponse getprice() throws Exception {
        return ApiResponse.create(JSONObject.toJSON(PancakeSwapLPQuery.getPrice()));
    }

    @Autowired
    private AppUserWalletService appUserWalletService;
    private BigDecimal userRate = new BigDecimal("0.1");
    private BigDecimal upRate = new BigDecimal("0.03");

    private BigDecimal amounts = new BigDecimal("1000");
    @Autowired
    private AppFundInfoMapper appFundInfoMapper;

    @Transactional
    public void addCAP(Integer userId, BigDecimal amount, String seq) throws Exception {
        PancakeSwapLPQuery.Price price = PancakeSwapLPQuery.getPrice();
        BigDecimal lpPrice = amount.multiply(price.getLp());
        if(lpPrice.compareTo(amounts)<0)return;
        BigDecimal bigDecimal = lpPrice.divide(price.getCap(),8,RoundingMode.DOWN);
        appUserWalletService.updateWallet(LetokenTokenTypeEnum.CAP.getId(),userId,bigDecimal.multiply(userRate),TokenTransactionTypeEnum.CAP_airdrop.getValue(),seq);

        Integer upId = appFundInfoMapper.getLevel(userId);
        if(upId !=null && !upId.equals(0)){
            appUserWalletService.updateWallet(LetokenTokenTypeEnum.CAP.getId(),upId,bigDecimal.multiply(upRate),TokenTransactionTypeEnum.CAP_airdrop_Community.getValue(),seq);
        }
    }



}
